package router

import (
	"log"
	"net/http"
	"poker/controller"
	"poker/env"
	"poker/middleware"
	"poker/ws"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"github.com/nlh1996/utils"
)

// Init .
func Init() {
	gin.SetMode(env.GlobalData.Server.Mode)
	router := gin.New()
	//router.Use(middleware.TLSHandler())
	router.Use(gin.Logger())
	router.Use(middleware.CrossDomain())
	router.SetTrustedProxies([]string{"127.0.0.1"})
	router.GET("/", Handler)

	api := router.Group("zhenren")
	{
		// api.POST(":channel/getOpenid", controller.GetOpenid)
		// api.POST(":channel/login", controller.Login)
		api.POST("/api/:channel/upload", controller.UpLoad)
		api.GET("/api/:channel/:id/data", controller.GetUserData)

		// 投票相关接口
		api.GET("/api/:channel/getRank", controller.GetRank)
		api.GET("/api/getGirls", controller.GetGirls)
		api.POST("/api/:channel/vote", controller.Vote)

		// 支付相关接口
		api.GET("/api/pay/callback", controller.TestPaySuccessCallback)
		api.POST("/api/pay/callback", controller.PaySuccessCallback)
		api.POST("/api/pay/order", controller.CreateOrder)
		api.GET("/api/pay/orders", controller.GetOrders)
		api.POST("/api/pay/order_resend", controller.ReSendOrder)
		api.POST("/api/pay/order_finish", controller.OrderFinish)

		// api.POST("/api/pay/get_balance", controller.GetBalance)
		// api.GET("/api/pay/queryPayState", controller.QueryPayState)
	}

	api2 := router.Group("api")
	{
		api2.POST("/:channel/upload", controller.UpLoad)
		api2.GET("/:channel/:id/data", controller.GetUserData)
	}

	router.Run(":" + utils.IntToString(env.GlobalData.Server.Port))
	// if env.GlobalData.Server.Mode == "debug" {
	// 	router.Run(":" + utils.IntToString(env.GlobalData.Server.Port))
	// } else {
	// 	if err := router.RunTLS(":"+utils.IntToString(env.GlobalData.Server.Port), "../ssl/enjoygaga.darknight.games_bundle.crt", "../ssl/enjoygaga.darknight.games.key"); err != nil {
	// 		log.Println("RunTLS error", err)
	// 	}
	// }
}

var (
	upGrader = websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	router *ws.Router
)

func init() {
	router = ws.NewRouter()
	// router.AddRouter(100, controller.Pipei)
}

// Handler .
func Handler(c *gin.Context) {
	// 验证连接安全
	uid := c.Query("uid")
	// token := c.Query("token")
	account := c.Query("account")
	// if err := validateToken(uid, token); err != nil {
	// 	return
	// }
	// 升级get请求为webSocket长连接
	connection, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println(err)
		return
	}
	conn, err := ws.NewConnection(connection, router, account, uid)
	if err != nil {
		connection.WriteMessage(websocket.TextMessage, []byte(err.Error()))
		return
	}
	// info.SetPlayerNum(1)
	conn.Start()
}

// token验证
func validateToken(uid string, token string) error {
	// 向账号服务器发起验证
	data, err := utils.HttpPost("https://", gin.H{"account": uid, "token": token})
	if err != nil {
		log.Println(data, err)
		return err
	}
	return nil
}
